package Service.Impl;

import java.io.InputStream;

import Dao.DepartmentDao;
import Model.Department;
import Model.DepartmentChanged;
import Service.DepartmentService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.*;

import utils.Excel;

@Service("DepartmentService")
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentDao departmentDao;

    //  获取全部信息
    @Override
    public List<Department> getAllDepartmentList() {
        System.out.println("service层：查看所有机构信息");
        return departmentDao.getAllDepartmentList();
    }

    //  获取全部变更信息
    public List<DepartmentChanged> getAllDepartmentChangedList(){
        System.out.println("service层：查看所有机构变更信息");
        return departmentDao.getAllDepartmentChangedList();
    }

    //  删除
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 30000, rollbackFor = {RuntimeException.class, Exception.class})
    public String delDepartment(int id) {
        System.out.println("service层：执行删除");
        Department department=departmentDao.searchdelete(id);
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        //departmentInfobyID.setDepartment_change_time(timestamp);
        department.setDepartment_change_time(timestamp);
        System.out.println("修改时间11："+department.getDepartment_change_time());
        //System.out.println("修改时间22："+departmentInfobyID.getDepartment_change_time());
        System.out.println("deparment的内容："+department);
//
//            修改前的数据

        int i=departmentDao.insertDel(department);


        int num = this.departmentDao.deleteByPrimaryKey(id);
        if (num < 1) {//事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "操作失败";
        }
        return "ok";
    }

    //    根据ID查询
    @Override
    public Department findDepartmentInfobyID(Integer id){
        return departmentDao.findDepartmentInfobyID(id);
    }

    //  搜索-信息页面
    @Override
    public List<Department> findDepartmentInfo(String departmentName,String regionCode,String status){
        System.out.println("service层："+departmentName);
        System.out.println("service层："+regionCode);
        System.out.println("service层："+status);
        System.out.println("service层：进入dao层");
//        System.out.println(regionCode);
        return departmentDao.findDepartmentInfo(departmentName,regionCode,status);
    }

    //  搜索-变更页面
    @Override
    public List<DepartmentChanged> findChangedInfo(String nameSearch,String settleCodeSearch,String titleSearch){
        System.out.println("service层："+nameSearch);
        System.out.println("service层："+settleCodeSearch);
        System.out.println("service层："+titleSearch);
        System.out.println("service层：进入dao层");
//        System.out.println(regionCode);
        return departmentDao.findChangedInfo(nameSearch,settleCodeSearch,titleSearch);
    }

    //  更新
    @Override
    public String updateDepartment(Department department, HttpSession session) {
        System.out.println("service层：状态："+department.getDepartment_status());
        System.out.println("service层：结算代码："+department.getDepartment_settlement_code());
        if (department.getId() != null) {
            if(department.getDepartment_settlement_code().length()==11){
                System.out.println("service层:验证无误/结算代码："+department.getDepartment_settlement_code());
//            根据ID找到修改前的数据
                Department departmentInfobyID=departmentDao.findDepartmentInfobyID(department.getId());
                System.out.println("service层:department的ID："+department.getId());
                System.out.println("service层:存在此机构");
//            记录修改时间
                Date date = new Date();
                Timestamp timestamp = new Timestamp(date.getTime());
                departmentInfobyID.setDepartment_change_time(timestamp);
                department.setDepartment_change_time(timestamp);
                System.out.println("修改时间11："+departmentInfobyID.getDepartment_change_time());
                System.out.println("修改时间22："+department.getDepartment_change_time());
                System.out.println("deparment的内容："+department);
//
//            修改前的数据
                Map<String,Object> oldDepartment = new HashMap<String,Object>();
                oldDepartment.put("department_name", departmentInfobyID.getDepartment_name());
                oldDepartment.put("department_phone_number", departmentInfobyID.getDepartment_phone_number());
                oldDepartment.put("department_address", departmentInfobyID.getDepartment_address());
                oldDepartment.put("department_settlement_scope", departmentInfobyID.getDepartment_settlement_code());
                oldDepartment.put("department_first_settle_date", departmentInfobyID.getDepartment_first_settle_date());
                oldDepartment.put("department_notification_date", departmentInfobyID.getDepartment_notification_date());
                oldDepartment.put("department_corporate", departmentInfobyID.getDepartment_corporate());
                oldDepartment.put("department_settlement_code", departmentInfobyID.getDepartment_settlement_code());
                oldDepartment.put("department_region_code", departmentInfobyID.getDepartment_region_code());
                oldDepartment.put("department_first_time", departmentInfobyID.getDepartment_first_time());
                oldDepartment.put("department_change_time", departmentInfobyID.getDepartment_change_time());
                oldDepartment.put("department_status", departmentInfobyID.getDepartment_status());
                System.out.println("service层:旧的数据：oldDepartment："+oldDepartment);

//            修改后的数据
                Map<String,Object> newDepartment = new HashMap<String,Object>();
                newDepartment.put("department_name", department.getDepartment_name());
                newDepartment.put("department_phone_number", department.getDepartment_phone_number());
                newDepartment.put("department_address", department.getDepartment_address());
                newDepartment.put("department_settlement_scope", department.getDepartment_settlement_code());
                newDepartment.put("department_first_settle_date", department.getDepartment_first_settle_date());
                newDepartment.put("department_notification_date", department.getDepartment_notification_date());
                newDepartment.put("department_corporate", department.getDepartment_corporate());
                newDepartment.put("department_settlement_code", department.getDepartment_settlement_code());
                newDepartment.put("department_region_code", department.getDepartment_region_code());
                newDepartment.put("department_first_time", department.getDepartment_first_time());
                newDepartment.put("department_change_time", department.getDepartment_change_time());
                newDepartment.put("department_status", department.getDepartment_status());
                System.out.println("service层:新的数据：newDepartment：："+newDepartment);

//              比较新旧数据
                for(Map.Entry<String,Object>entry:oldDepartment.entrySet()){
//                获取当前键值
                    String keyContent=entry.getKey();
                    System.out.println("获取的key值："+keyContent);
//                获取当前键值的value值（新+旧）
                    Object oldValue=entry.getValue() ==null?"":entry.getValue();
                    Object newValue=newDepartment.get(entry.getKey())==null?"":newDepartment.get(entry.getKey());
                    System.out.println("比较循环前的数据（旧）："+oldValue);
                    System.out.println("比较循环前的数据（新）："+newValue);
//                比较：如果二者value不同
                    if(!oldValue.equals(newValue)){
                        System.out.println("不同的数据（旧）："+oldValue);
                        System.out.println("不同的数据（新）："+newValue);
                        System.out.println("不同");
//                    建表
                        Map<String,Object> insertInfo = new HashMap<String,Object>();
                        switch (keyContent){
                            case "department_name": insertInfo.put("department_changed_title","机构名称");break;
                            case "department_phone_number": insertInfo.put("department_changed_title","联系电话");break;
                            case "department_address":insertInfo.put("department_changed_title","机构地址");break;
                            case "department_settlement_scope":insertInfo.put("department_changed_title","结算范围");break;
                            case "department_first_settle_date":insertInfo.put("department_changed_title","首次可结算日期");break;
                            case "department_notification_date":insertInfo.put("department_changed_title","交易代码下发通知书日期");break;
                            case "department_corporate":insertInfo.put("department_changed_title","法人");break;
                            case "department_settlement_code":insertInfo.put("department_changed_title","结算代码");break;
                            case "department_region_code":insertInfo.put("department_changed_title","区内编码");break;
                            case "department_first_time":insertInfo.put("department_changed_title","创建时间");break;
                            case "department_status":insertInfo.put("department_changed_title","状态");break;
                        }
                        insertInfo.put("department_name", department.getDepartment_name());
                        insertInfo.put("department_settlement_code", department.getDepartment_settlement_code());
                        insertInfo.put("department_change_time", department.getDepartment_change_time());
                        insertInfo.put("start_change_date",department.getStart_change_date());
                        insertInfo.put("department_new_content", newValue);
                        insertInfo.put("department_history_content", oldValue);
                        System.out.println("变更后的表："+insertInfo);
                        System.out.println("进入dao层：InsertHistoryChange");
//                    以哈希表形式传入更改后的数据
                        this.departmentDao.InsertHistoryChange(insertInfo);
                    }else{
//                    若value相同，则不传
                        System.out.println("相同的数据（旧）："+oldValue);
                        System.out.println("相同的数据（新）："+newValue);
                        System.out.println("相同");
                    }
                }
//            更新数据
                this.departmentDao.updateById(department);
                System.out.println("update成功（Impl）");
            } else{
                System.out.println("校验失败：结算代码的长度为："+department.getDepartment_settlement_code());
                return "errorSettleCode";
            }
        }
        return "ok";
    }

//    @Resource
//    private ExcelMapper excelMapper;

    //  导入excel
    @Override
    public String InputExcel(InputStream is, String originalFilename) {
        System.out.println("service层：传入excel文件");
        Map<String,Map<String,Object>> param = new HashMap<String,Map<String,Object>>();
        Map<String,Object> ginsengMap = new HashMap<String,Object>();
        List<ArrayList<Object>> list;
        if (originalFilename.endsWith(".xls")) {
            System.out.println("service层：是2003版的excel");
            list = Excel.readExcel2003(is);
        } else {
            System.out.println("service层：是2007版的excel");
            list = Excel.readExcel2007(is);
        }
        for (int i=0,j=list.size();i<(j-1);i++){
            List<Object> row = list.get(i);
            System.out.println("service层：当前i= "+i);
            System.out.println("service层：当前row= "+row);
//            ginsengMap.put("id", row.get(0).toString());
            ginsengMap.put("department_name", row.get(1).toString());
            ginsengMap.put("department_phone_number", row.get(2).toString());
            ginsengMap.put("department_address", row.get(3).toString());
            ginsengMap.put("department_settlement_scope", row.get(4).toString());
            ginsengMap.put("department_first_settle_date", row.get(5).toString());
            ginsengMap.put("department_notification_date", row.get(6).toString());
            ginsengMap.put("department_corporate", row.get(7).toString());
            ginsengMap.put("department_settlement_code", row.get(8).toString());
            ginsengMap.put("department_region_code", row.get(9).toString());
            ginsengMap.put("department_first_time", row.get(10).toString());
            ginsengMap.put("department_change_time", row.get(11).toString());
            ginsengMap.put("department_status", row.get(12).toString());
            param.put("keys", ginsengMap);
            departmentDao.InputExcel(param);
            System.out.println("service层：inputExcel成功");
        }
        return "01";
    }

    //  导出excel
    @Override
    public List<Department> OutputExcel() { return departmentDao.getAll(); }

    //  excel-获取全部内容
    @Override
    public List<Department> getAll() {
        return departmentDao.getAll();
    }

    //根据结算代码找到机构——制定派工单页面
    @Override
    public List<Department> findOrgInfobySettleCode(String settleCode){
        return departmentDao.findOrgInfobySettleCode(settleCode);
    }
}

